package com.rzico.sbl.ui.statistic

import android.widget.ImageView
import androidx.core.view.isVisible
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityUnionGoodsBinding
import com.rzico.sbl.model.FilterData
import com.rzico.sbl.model.HomeContent
import com.rzico.sbl.model.UnionFilter
import com.rzico.sbl.other.*
import com.rzico.sbl.viewmodel.StatisticUnionViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.helper.intValue
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.showTimeRangeDialog
import com.xinnuo.slimadapter.SlimAdapter

class UnionGoodsActivity : BaseActivity(R.layout.activity_union_goods) {

    private val mBinding by lazy { ActivityUnionGoodsBinding.bind(getRootView()) }

    private var mOrderType = ""
    private var mEnterpriseId = ""
    private var mEnterpriseName = ""
    private var mBeginDate = getFirstDate()
    private var mEndDate = getEndDate()

    private val mStationList = ArrayList<UnionFilter>()
    private val mFilterList = ArrayList<FilterData>()

    override fun getViewModel() = get<StatisticUnionViewModel>()

    override fun initData() {
        initTitle(title = "商品统计")

        initLayout()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
        getStationList()
    }

    private fun initLayout() {
        mBinding.listLayout.apply {
            emptyLayout.also {
                it.emptyHint.text = "暂无相关商品信息！"
            }

            recycleList.also { view ->
                view.loadLinear(
                    refresh = swipeRefresh,
                    onRefresh = { getData(0) },
                    onLoad = {
                        isLoadingMore
                            .conditionFalse {
                                isLoadingMore = true
                                getData(pageNum)
                            }
                    }
                )

                view.addItemDecoration(SpaceTBDecoration(hasHeader = false))

                mAdapter = SlimAdapter.creator()
                    .register<HomeContent>(R.layout.item_statistic_goods) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_goods_name, bean.name)
                            text(R.id.item_goods_type, "规格：${bean.spec}")
                            text(R.id.item_goods_price, "单价：${bean.price.formatDecimal()} 元")
                            text(R.id.item_goods_num, bean.quantity)
                            text(R.id.item_goods_num_hint, "数量：")

                            with<ImageView>(R.id.item_goods_logo) {
                                it.loadImage(bean.thumbnail)
                            }
                        }
                    }
                    .attachTo(view)
            }
        }
    }

    override fun initListener() {
        mBinding.apply {
            getViewModel().mFilterTime[3].isChecked = true

            when (mOrderType) {
                "in" -> {
                    goodsType.text = "接收商品"
                    getViewModel().mTypeGoods[1].isChecked = true
                }
                else -> {
                    mOrderType = "out"
                    goodsType.text = "转出商品"
                    getViewModel().mTypeGoods[0].isChecked = true
                }
            }

            goodsTypeLl
                .oneClick {
                    getViewModel()
                        .showDropFilter(
                            getIContext(),
                            goodsTop,
                            getViewModel().mTypeGoods,
                            goodsType,
                            goodsTypeArrow
                        ) {
                            goodsType.setTextColor(getColorEx(R.color.colorAccent))
                            goodsTypeArrow.setImageResource(R.mipmap.icon_member02)

                            mOrderType = it.id

                            // 清除站点
                            mEnterpriseId = ""
                            goodsZhan.text = "选择站点"
                            goodsZhan.setTextColor(getColorEx(R.color.black))
                            goodsZhanArrow.setImageResource(R.mipmap.icon_member01)
                            getStationList()

                            updateList()
                        }
                }

            goodsZhanLl
                .oneClick {
                    getViewModel()
                        .showDropFilter(
                            getIContext(),
                            goodsTop,
                            mFilterList,
                            goodsZhan,
                            goodsZhanArrow
                        ) {
                            if (it.id.isEmpty()) {
                                goodsZhan.setTextColor(getColorEx(R.color.black))
                                goodsZhanArrow.setImageResource(R.mipmap.icon_member01)
                            } else {
                                goodsZhan.setTextColor(getColorEx(R.color.colorAccent))
                                goodsZhanArrow.setImageResource(R.mipmap.icon_member02)
                            }

                            mEnterpriseId = it.id
                            mEnterpriseName = it.name
                            updateList()
                        }
                }

            goodsTimeLl
                .oneClick {
                    getViewModel()
                        .showDropTimeFilter(
                            getIContext(),
                            goodsTime,
                            goodsTimeArrow,
                            goodsTop,
                            getViewModel().mFilterTime
                        ) { bean ->

                            (bean.id != "7")
                                .condition {
                                    getViewModel()
                                        .mFilterTime
                                        .last()
                                        .name = "自定义时间"
                                }

                            when (bean.id) {
                                "1" -> {
                                    mBeginDate = getTodayDate()
                                    mEndDate = getTodayDate()

                                    getStationList()
                                    updateList()
                                }
                                "2" -> {
                                    mBeginDate = getBeforeDate()
                                    mEndDate = getBeforeDate()

                                    getStationList()
                                    updateList()
                                }
                                "3" -> {
                                    mBeginDate = getBeforeDate(6)
                                    mEndDate = getTodayDate()

                                    getStationList()
                                    updateList()
                                }
                                "4" -> {
                                    mBeginDate = getFirstDate()
                                    mEndDate = getEndDate()

                                    getStationList()
                                    updateList()
                                }
                                "5" -> {
                                    mBeginDate = getBeforeFirstDate()
                                    mEndDate = getBeforeEndDate()

                                    getStationList()
                                    updateList()
                                }
                                "6" -> {
                                    mBeginDate = getYearFirstDate()
                                    mEndDate = getYearEndDate()

                                    getStationList()
                                    updateList()
                                }
                                "7" -> {
                                    showTimeRangeDialog(
                                        isCurrentDate = true,
                                        isAfterLimited = true,
                                        onResult = { start, end ->
                                            getViewModel()
                                                .mFilterTime
                                                .forEach { it.isChecked = false }

                                            getViewModel()
                                                .mFilterTime
                                                .last()
                                                .isChecked = true

                                            mBeginDate = start
                                            mEndDate = end
                                            bean.name = "$mBeginDate ~ $mEndDate"
                                            goodsTime.text = bean.name

                                            getStationList()
                                            updateList()
                                        }
                                    )
                                }
                            }
                        }
                }
        }
    }

    /**
     * 水站列表
     */
    private fun getStationList() {
        getViewModel()
            .goodsFilterList(
                type = mOrderType,
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = { list ->
                    mStationList.clear()
                    mStationList.addItems(list)

                    mFilterList.apply {
                        clear()

                        add(
                            FilterData(
                                "全部",
                                "",
                                "选择站点",
                                mEnterpriseId.isEmpty()
                            )
                        )

                        mStationList
                            .mapTo(this) {
                                FilterData(
                                    it.name.orEmpty(),
                                    it.enterpriseId,
                                    it.name.orEmpty()
                                )
                            }

                        mEnterpriseId
                            .notEmpty {
                                this@apply
                                    .firstOrNull { it.id == this }
                                    ?.let {
                                        it.name = mEnterpriseName
                                        it.hint = mEnterpriseName
                                        it.isChecked = true
                                    }
                                    ?: kotlin.run {
                                        add(
                                            FilterData(
                                                mEnterpriseName,
                                                this,
                                                mEnterpriseName,
                                                true
                                            )
                                        )
                                    }
                            }
                    }
                }
            )
    }

    /**
     * 联盟商品统计列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .goodsList(
                page = index,
                type = mOrderType,
                enterpriseId = mEnterpriseId,
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    mList.apply {
                        (index == 0)
                            .condition {
                                clear()
                                pageNum = 0
                            }

                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    mBinding
                        .apply {
                            mEnterpriseId
                                .isEmpty()
                                .conditionElse(
                                    actionTrue = {
                                        goodsTotal.text =
                                            mStationList
                                                .sumOf { it.subQuantity.intValue }
                                                .toString()

                                        goodsNum.text = mStationList.size.toString()
                                    },
                                    actionFalse = {
                                        mStationList
                                            .firstOrNull { it.enterpriseId == mEnterpriseId }
                                            ?.let {
                                                goodsTotal.text = it.subQuantity
                                                goodsNum.text = "1"
                                            }
                                            ?: kotlin.run {
                                                goodsTotal.text = "0"
                                                goodsNum.text = "0"
                                            }
                                    }
                                )
                        }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}